/**Author:7rATM Team
 *Date:May 2009
 *Description: The class BankAccountDBIO read and write the database of BankAccountDB,
 *             
 */
package AtmSystem;

import java.util.*;
import java.io.*;

public class BankAccountDBIO {



    public BankAccountDB loadBankAccountDB (String filename) throws IOException,
        FileNotFoundException {

        BankAccountDB myBankAccountDB = new BankAccountDB();
        //read the database file to BankAccountDB a line at a time
        BufferedReader reader =
            new BufferedReader(new FileReader(filename));
        String line =  reader.readLine();
        //if the line readed is not null,add it to myBankAccountDB
        while (line != null) {

            BankAccount myBankAccount = null;
            myBankAccount = readBankAccount(line);
            myBankAccountDB.add(myBankAccount);

            line =  reader.readLine();
        }

		reader.close();

        return myBankAccountDB;
    }


    private BankAccount readBankAccount (String line) {
       /**
	* read the information of account
	* card number and balance
	*/
        StringTokenizer tokenizer = new StringTokenizer(line, ",");
		
		int cardNumber = Integer.parseInt(tokenizer.nextToken());
		double balance = Double.parseDouble(tokenizer.nextToken());

        BankAccount myBankAccount =new BankAccount ( cardNumber, balance);
		return myBankAccount;

	  }
         /**
	  *if the bankaccount is exit write the information of it
	  * catch exceptions if file is not exit
	  */
	  public boolean writerBankAccountDB (String filename ,BankAccountDB newBankAccountDB) throws IOException,
        FileNotFoundException {
	 try
     {
		PrintWriter writer=
            new PrintWriter (new FileWriter(filename,false));

        for (int index = 0; index <newBankAccountDB.getNumbers();index++ )
			{
			BankAccount myBankAccount= newBankAccountDB.get(index);
			writer.println(writeBankAccount(myBankAccount));
			} 
			writer.close();

        return true;
		}
     catch (FileNotFoundException e)
		{
		 return false;
		}   
	}

               /**
	        * return the information of bank account
		* write the information of account
		* card number and balance
		* @return bankAccountInfo
		*/
   private String writeBankAccount(BankAccount newBankAccount) {

		String bankAccountInfo="";
		bankAccountInfo+= newBankAccount.getCardNumber();
		bankAccountInfo+= ",";
		bankAccountInfo+= newBankAccount.getBalance();
		
      return bankAccountInfo;      
	}
}
